  LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE ieee.numeric_std.ALL; 



ENTITY pwm IS

 GENERIC(
	CONSTANT c_base_adress : std_logic_vector(15 downto 0) := X"1300" -- adresse de base du module( chacun des registres du module est une position relative a cette adresse)
	);

PORT(
	clk: IN std_logic;
	reset: IN std_logic;
	
	-- comm avec le bus interne
	adresse : IN std_logic_vector(15 downto 0) ;
	data_in : IN std_logic_vector(7 downto 0);
	data_out : OUT std_logic_vector(7 downto 0);
	read : IN std_ulogic;
	write : IN std_logic;
	
	pwm : OUT std_ulogic
	);
END;

ARCHITECTURE Eirbot OF  pwm IS


-- diviseur de freq de la pwm
SIGNAL s_periode_pwm : std_logic_vector(2 DOWNTO 0); 

-- signal recueillant la pwm
SIGNAL s_pwm : std_ulogic;

-- 
SIGNAL s_clk : std_ulogic;

BEGIN

pwm <= s_pwm;
s_periode_pwm <= data_in(2 DOWNTO 0) WHEN adresse(15 DOWNTO 2) = c_base_adress(15 downto 2) AND write = '0' --"00010011111000" AND write = '0';
				ELSE "010" WHEN reset = '0';
--<<<==========================================>>>--
clk_2_Hz : process(clk, reset)
	VARIABLE v_cpt : natural range 0 to 12500000;
BEGIN
	IF rising_edge(clk) THEN--
	
		v_cpt := v_cpt +1;
		IF ( v_cpt = 1250000 ) THEN -- on met a jour les parametres de la pwm uniquement en debut de periode
			s_clk <= not(s_clk);
			v_cpt := 0;
		END IF;
		
	END IF;
END PROCESS clk_2_Hz;

--<<<==========================================>>>--

process_generation_pwm : process (clk, reset, s_periode_pwm)
	VARIABLE v_cpt_pwm : natural  range 0 to 50000000;
BEGIN
	IF reset = '0' THEN
		s_pwm <= '0';
		v_cpt_pwm := 0;
		
	ELSIF rising_edge(clk) THEN
		
		v_cpt_pwm := v_cpt_pwm +1;
		
		IF ( v_cpt_pwm = 12500000) THEN--v_cpt_pwm = to_integer( unsigned(s_periode_pwm(2 downto 0))) ) THEN
			s_pwm <= not(s_pwm);
			v_cpt_pwm := 0;
		END IF;				
	
	END IF;
END PROCESS process_generation_pwm;

--<<<==========================================>>>--

END;

